<!-- 蓝色登录页面2 -->
<template>
    
        <view style="height:100vh;background: #fff;">
            <view class="img-a">
                <view class="t-b">
                    您好，
                    <br />
                    欢迎登录~
                </view>
            </view>
            <view class="login-view" style="">
                <view class="t-login">
                    <u-form :model="formData" ref="uForm" label-width="160" label-position="top"
                        :label-style="{fontSize:'36rpx',fontWeight: 'bold'}">
                        
                        <u-form-item label="服务器地址" prop="baseApiUrl" v-show="formData.baseApiUrl == '' || isShowBaseApiUrl == true ">
                            <!-- <u-input v-model="formData.baseApiUrl" placeholder="域名或IP:端口" clearable ></u-input> -->
                            
                            <uni-combox :candidates="apiUrlData" placeholder="域名或IP:端口" v-model="formData.baseApiUrl" style="border:none !important;width:100% !important;" ></uni-combox>
                            <u-icon class="u-icon" name="scan" size="45" @click="startScan"></u-icon>
                            
                        </u-form-item>

                        <u-form-item label="座席号" prop="seat">
                            <u-input v-model="formData.seat" placeholder="请输入您的座席号" clearable ></u-input>
                        </u-form-item>
                        <u-form-item label="密码" prop="pwd">
                            <u-input v-model="formData.pwd" type="password" placeholder="请输入您的密码" clearable ></u-input>
                        </u-form-item>
                        <view style="width:100%;margin-top:20rpx;height:40rpx;">
                            <view style="float:left;width:40%;">
                                <u-checkbox v-model="formData.save_pwd">记住密码</u-checkbox>
                            </view>
                            
                            <view style="margin-top:15rpx;float:right;text-align: right;width:40%;" @click="handleChangeShowBaseApiUrl()">
                                <u-icon class="u-icon" name="moments" size="35" ></u-icon>
                                <text style="font-size:32rpx;margin-left:15rpx;">服务器地址</text>
                            </view>
                        </view>

                        <u-button @click="$stopClicks.noMultipleClicks(login)" shape="circle" :ripple="true" type="primary" style="margin-top: 35px;">登 录</u-button>
                        
                        <view class="app_version">
                            <text>版本号:{{loginParams['应用版本名称']}}</text>
                        </view>
                        
                    </u-form>
                </view>
            </view>
        </view>

</template>
<script>
	import {
		postLogin
	} from '@/api/auth.js';
	
	import {
		mapGetters,mapState
	} from "vuex";
        
	export default {
		data() {
			return {
				formData: {
					seat: uni.getStorageSync("username"), //座席号
					pwd: uni.getStorageSync("pwd"), //密码
					baseApiUrl:uni.getStorageSync("baseApiUrl"), //服务器接口地址，
					save_pwd:true
				},
				formRules: {
					seat: [{
						required: true,
						message: '请输入您的座席号',
						trigger: 'blur'
					}],
					pwd: [{
						required: true,
						message: '请输入您的密码',
						trigger: 'blur'
					}],
                    baseApiUrl: [{
                    	required: true,
                    	message: '请输入服务器地址',
                    	trigger: 'blur'
                    }],
				},
				isShowBaseApiUrl:true,
                
                apiUrlData:[],
                
                loginParams:{}
			};
		},
		computed: {
			...mapGetters(["callTaskTimer","callTaskCountTimer","taskType","PageCur"]),
			...mapState({
				callTaskTimer: state => state.task.callTaskTimer,
				callTaskCountTimer:state=>state.task.callTaskCountTimer,
				taskType:state => state.task.taskType,
				PageCur:state => state.tabbar.PageCur
			} )
		},
		onShow() {
			let token = uni.getStorageSync("token");
			let userinfo = uni.getStorageSync("userInfo");
			
			console.log("login onshow token",token);
			console.log("login onshow userinfo",userinfo);
			
			if(uni.getStorageSync("baseApiUrl") != ''){
				this.isShowBaseApiUrl = false;
			}
			
			//获取APP版本号数据
            const systemInfo = uni.getSystemInfoSync();
            console.log("login onshow systeminfo",systemInfo);
            
            this.loginParams['设备类型'] = systemInfo['deviceType'];
            this.loginParams['设备品牌'] = systemInfo['deviceBrand'];
            this.loginParams['设备型号'] = systemInfo['deviceModel'];
            this.loginParams['系统名称'] = systemInfo['osName'];
            this.loginParams['操作系统版本'] = systemInfo['osVersion'];
            this.loginParams['rom名称'] = systemInfo['romName'];
            this.loginParams['rom版本'] = systemInfo['romVersion'];
            this.loginParams['应用版本名称'] = systemInfo['appVersion'];
            this.loginParams['应用版本号'] = systemInfo['appVersionCode'];
            
            //保存版本号
            uni.setStorageSync("appVersionCode",systemInfo['appVersionCode']);
            
            
            //如果有TOKEN自动登录，提交登录接口，判断是否过期或在其它设备登录
            if (token) {
            	this.$store.dispatch("setPageCur",'index');
            	uni.navigateTo({
            		url: '/pages/index/tabbar?time='+(new Date()),
            	})
                
                
                // console.log("login onshow postlogin params",{'token':token.token,'loginParams':this.loginParams});
                // postLogin({...token,'loginParams':JSON.stringify(this.loginParams)}).then(res=>{
                //     console.log("login onshow postLogin",res);
                // 	if (res.data.code == 200) {
                // 		let data = res.data.data;
                		
                // 		this.$store.dispatch("setUserInfo", data);
                // 		uni.setStorageSync("token", data);
                // 		uni.setStorageSync("username",this.formData.seat);
                		
                // 		if(this.formData.save_pwd == true){
                // 			uni.setStorageSync("pwd",this.formData.pwd);
                // 		}else{
                // 			uni.setStorageSync("pwd","");
                // 		}
                		
                // 		uni.setStorageSync("taskType",1);
                // 		this.$store.dispatch("setTaskType",1);
                		
                // 		this.$store.dispatch("setPageCur","index");
                		
                // 		uni.reLaunch({
                // 			url: '/pages/index/tabbar?time=' + (new Date()),
                // 		});
                // 	} else {
                // 		uni.showToast({
                // 			title: res.data.msg,
                // 			icon: 'none'
                // 		});
                // 	}
                // }).catch(e => {
                // 	console.log("login e",e);
                // 	uni.showToast({
                // 		title: '系统超时!',
                // 		icon: 'error'
                // 	});
                // });
            }
            
            //获取历史服务器地址
            let api_url_data = uni.getStorageSync("baseApiUrlData");
            console.log("api_url_data",api_url_data);
            if(api_url_data != undefined && api_url_data != "" && api_url_data != null){
                this.apiUrlData = JSON.parse(api_url_data);
            }
		},
		methods: {
            //扫码获取服务器地址
            startScan(){
                uni.scanCode({
                    onlyFromCamera: true,     // 仅允许摄像头扫码（禁用相册）
                    scanType: ["qrCode"],     // 只识别二维码
                    success: res => {
                        console.log("扫码成功:", res);
                        // this.scanResult = res.result; // 获取结果字符串
                        
                        this.formData.baseApiUrl = res.result;
                    },
                    fail: err => {
                        console.error("扫码失败:", err);
                        uni.showToast({
                            title: "扫码失败",
                            icon: "none"
                        });
                    }
                });
            },
            
            
			//当前登录按钮操作
			login() {
				var that = this;
				let params = this.$u.deepClone(this.formData);
				params.pwd = this.formData.pwd;
                
                params.loginParams = JSON.stringify(this.loginParams);
                
                if(this.formData.baseApiUrl == ''){
                    uni.showToast({
                    	title: '请输入服务器地址!',
                    	icon: 'none'
                    });
                    
                    return;
                }
                
                if(this.formData.seat == ''){
                    uni.showToast({
                    	title: '请输入坐席工号!',
                    	icon: 'none'
                    });
                    
                    return;
                }
                
                if(this.formData.pwd == ''){
                    uni.showToast({
                    	title: '请输入密码!',
                    	icon: 'none'
                    });
                    
                    return;
                }
				
				//先修改服务器数据
				uni.setStorageSync("baseApiUrl",this.formData.baseApiUrl);
                
                //获取录音目录
                plus.io.requestFileSystem(
                    plus.io.PRIVATE_DOC, // 私有文档目录（对应 _doc 路径）
                    (fs) => {
                      // 定义目录路径（示例：在 _doc 下创建 myFolder）
                      let dirPath = 'logs';
                            
                      // 检查并创建目录
                      fs.root.getDirectory(
                        dirPath,
                        { create: true }, // 自动创建目录
                        (entry) => {
                            console.log('登录--创建文件夹成功:',entry.fullPath);
                            _this.$console.info('登录--创建文件夹成功:',entry.fullPath);
                            uni.setStorageSync("record_files",entry.fullPath);
                }, function(e) {
                        console.log('登录--创建文件夹失败:',e.message);
                        _this.$console.info('登录--创建文件夹失败:',e.message);
                    });
                }, function(e) {                    
                    console.log('登录--请求文件系统失败:',e.message);
                    _this.$console.info('登录--请求文件系统失败:',e.message);
                });
				
				console.log("formdata",this.formData,params);
                
                //服务器IP保存
                if(this.apiUrlData.indexOf(this.formData.baseApiUrl) == -1){
                    this.apiUrlData.push(this.formData.baseApiUrl);
                    
                    uni.setStorageSync("baseApiUrlData",JSON.stringify(this.apiUrlData));
                }
				
				postLogin(params).then(res => {
					console.log("postLogin",res);
					if (res.data.code == 200) {
						let data = res.data.data;
						
						this.$store.dispatch("setUserInfo", data);
						uni.setStorageSync("token", data);
						uni.setStorageSync("username",this.formData.seat);
						
						if(this.formData.save_pwd == true){
							uni.setStorageSync("pwd",this.formData.pwd);
						}else{
							uni.setStorageSync("pwd","");
						}
						
						uni.setStorageSync("taskType",1);
						this.$store.dispatch("setTaskType",1);
						
						this.$store.dispatch("setPageCur","index");
						
						uni.reLaunch({
							url: '/pages/index/tabbar?time=' + (new Date()),
						});
					} else {
						uni.showToast({
							title: res.data.msg,
							icon: 'none'
						});
					}
				}).catch(e => {
					console.log("login e",e);
					uni.showToast({
						title: '系统超时!',
						icon: 'error'
					});
				});
			},
            
            //显示隐藏服务器地址
            handleChangeShowBaseApiUrl(){
                this.isShowBaseApiUrl = !this.isShowBaseApiUrl;
            }

		},
		onReady() {
			this.$refs.uForm.setRules(this.formRules);
		}
	};
</script>
<style>    

	.img-a {
		width: 100%;
		height: 450rpx;
		background-image: url("../../static/login_top.png");
		background-size: 100%;
	}
	
	.login-view {
		width: 100%;
		position: relative;
		margin-top: -120rpx;
		background-color: #ffffff;
		border-radius: 8% 8% 0% 0;
	}

	.t-login {
		width: 600rpx;
		margin: 0 auto;
		font-size: 28rpx;
		padding-top: 80rpx;
	}

	.t-login .t-a {
		position: relative;
	}

	.t-b {
		text-align: left;
		font-size: 42rpx;
		color: #ffffff;
		padding: 130rpx 0 0 70rpx;
		font-weight: bold;
		line-height: 70rpx;
	}

	.t-login .t-c {
		position: absolute;
		right: 22rpx;
		top: 22rpx;
		background: #5677fc;
		color: #fff;
		font-size: 24rpx;
		border-radius: 50rpx;
		height: 50rpx;
		line-height: 50rpx;
		padding: 0 25rpx;
	}

	.t-login .t-d {
		text-align: center;
		color: #999;
		margin: 80rpx 0;
	}

	.t-login .t-e {
		text-align: center;
		width: 250rpx;
		margin: 80rpx auto 0;
	}

	.t-login .t-g {
		float: left;
		width: 50%;
	}

	.t-login .t-e image {
		width: 50rpx;
		height: 50rpx;
	}
    
    .app_version{
        width:100%;
        margin-top:20px;
        float:left;
        clear:both;
    }
    .app_version text{
        width: 100%;
        display: block;
        text-align: center;
        font-size:14px;
        color: #9f9f9f;
    }
</style>